/**
 * @copyright 2018 sinping.com 北京芯平科技股份有限公司. All rights reserved.
 * 本内容仅限于北京芯平科技股份有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */
package com.sinping.qh.utils.time;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.Date;

/**
 * 年龄计算
 *
 * @author limx
 * @create 2018/1/30
 */
public class BirthdayUtil {
    private static final Logger logger = LoggerFactory.getLogger(BirthdayUtil.class);

    public static int getAge(Date birthDay) {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            } else {
                age--;
            }
        }
        logger.info("age:" + age);
        return age;
    }

    public static void main(String[] args) throws Exception {
        //String bd = IdCardUtils.getDateOfBirthFromIDCard("130633200001012222");

        Date birthDay = DateFormatUtil.pareDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, "2000-01-01 00:00:00"); //IdCardUtils.getDateOfBirthFromIDCard("130633200001015290") + " 00:00:00");
    }
}